<template>
  <layout title="上传货品照片">
    <view class="good-photo">
      <view class="pre-box">
        <view class="pre-item" v-for="(item, index) in imageList" :key="index">
          <image
            class="pre-item-remove"
            :src="getImgSrc('/hall/icon_delete2@2x.png')"
            mode="aspectFill"
            @tap="remove(index)"
          ></image>
          <image
            class="pre-item-image"
            :src="item.url"
            mode="aspectFill"
          ></image>
        </view>
        <view
          v-if="imageList.length < 6"
          class="slot-btn"
          hover-class="slot-btn__hover"
          hover-stay-time="150"
          @tap="chooseImage"
        >
          <image
            class="add-btn"
            :src="getImgSrc('/hall/photo@2x.png')"
            mode="aspectFill"
          />
          <view>{{ imageList.length }}/6</view>
        </view>
      </view>

      <!-- <u-upload ref="uUpload" :custom-btn="true" :show-upload-list="showUploadList" :action="action"
				:auto-upload="false" name="files" :header="header" del-icon="close-circle" :max-count="6" @on-list-change="console">
				<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
					<image class="add-btn" :src="getImgSrc('/hall/photo@2x.png')" mode="aspectFill" />
					<view>{{imageList.length}}/6</view>
				</view>
			</u-upload> -->

      <template>
        <u-modal
          v-model="confirmModal"
          :show-title="false"
          :mask-close-able="false"
          :show-confirm-button="false"
          :closeable="false"
          :show-cancel-button="false"
        >
          <view class="slot-content">
            <view class="task-modal">
              <image
                class="task-modal-icon"
                :src="getImgSrc('/hall/icon_close@2x.png')"
                @tap="confirmModal = false"
              />
              <view class="task-modal-head">确认取货后不可撤销！</view>
              <view class="task-modal-body">
                <view class="task-modal-desc concat">请确定是否取货</view>
                <!-- <input
                  v-model="over.logisticsCode"
                  class="task-modal-input"
                  placeholder="请输入快递公司（必填）"
                  placeholder-class="task-modal-place"
                />
                <input
                  v-model="over.logisticsName"
                  class="task-modal-input"
                  placeholder="请输入快递单号（必填）"
                  placeholder-class="task-modal-place"
                /> -->
                <textarea
                  v-model="over.memo"
                  class="task-modal-area"
                  placeholder="请输入订单备注（选填）"
                  placeholder-class="task-modal-place"
                />
                <button class="task-modal-use" @tap="confirmOver">
                  确定已取货
                </button>
              </view>
            </view>
          </view>
        </u-modal>
      </template>

      <button class="upload-btn" @tap="triggerToUpload">上传</button>
    </view>
  </layout>
</template>

<script>
import { readImg, compressImg } from "@/common/minizerImg.js";

export default {
  name: "task",
  components: {},
  props: {},
  data() {
    return {
      no: "",
      code: "",
      type: "",
      imageList: [],
      confirmModal: false,
      over: {
        expressId: "",
        expressCompany: "",
        memo: "",
      },
    };
  },
  computed: {
    action() {
      return [
        this.vuex_config.baseUrl,
        "applet/runner/index/photo",
        this.no,
        this.code,
      ]
        .filter((d) => Boolean(d))
        .join("/");
    },
    header() {
      return {
        Authorization: this.vuex_tokenHead + this.vuex_token,
      };
    },
  },
  onLoad(option) {
    this.no = option.no;
    if (option.code === "null" || option.code === "undefined") {
      this.code = null;
    } else {
      this.code = option.code;
    }
    this.type = option.type; // 0 送件, 1 取件
  },
  onReady() {
    // this.imageList = this.$refs.uUpload.lists;
  },
  methods: {
    async compress(file) {
      const img = await readImg(file);
      const blob = await compressImg(img, file.type, 1000, 1000);
      return blob;
    },
    console(a) {
      console.log(a);
    },
    remove(index) {
      this.imageList.splice(index, 1);
    },
    chooseImage() {
      const that = this;
      uni.chooseImage({
        success(e) {
          (async function () {
            const list = await Promise.all(
              e.tempFiles.map(async (tempFile, idx) => ({
                file: await that.compress(tempFile),
                url: e.tempFilePaths[idx],
              }))
            );
            that.imageList = that.imageList.concat(list);
          })();
        },
      });
    },
    async confirmOver() {
      await this.$u.api.invokeHallTaskConfirmReceived({
        message: this.over.memo,
        no: this.no,
        code: this.code,
      });
      uni.showToast({
        title: "提交成功",
      });

      await new Promise((r) => setTimeout(r, 1000));

      uni.navigateBack({
        delta: 1,
      });
    },
    async triggerToConfirm() {
      this.confirmModal = true;
    },
    async triggerToUpload() {
      await this.upload();
      if (Number(this.type) === 0) {
        this.back();
      } else {
        await this.triggerToConfirm();
      }
    },
    async uploadImg(imgFile) {
      const file = await this.compress(imgFile);
      return new Promise((resolve, rej) => {
        uni.uploadFile({
          url: this.vuex_config.baseUrl + "/applet/oss/upload",
          file,
          header: {
            Authorization: this.vuex_tokenHead + this.vuex_token,
          },
          name: "file",
          formData: {
            type: "IMG_USER_CARD",
          },
          success: (res) => {
            const data = JSON.parse(res.data);
            if (data.code !== 200) {
              uni.showToast({
                title: data.message,
                icon: "none",
              });
              return;
            }
            resolve(data.data);
          },
          fail: (err) => {
            rej();
            console.log("上传失败");
          },
          complete: console.log,
        });
      });
    },
    upload() {
      const _this = this;
      return new Promise((resolve, rej) => {
        if (!this.imageList.length) {
          uni.showToast({
            title: "请上传货品照片",
            duration: 2000,
            icon: "none",
          });
          rej();
          return;
        }

        const results = this.imageList.map((img) => {
          return this.uploadImg(img.file);
        });
        Promise.all(results).then((res) => {
          _this.$u
            .put(_this.action, res, {
              "content-type": "application/json",
            })
            .then((res) => {
              if (res.code === 200) {
                uni.showToast({
                  title: "上传成功",
                  duration: 2000,
                });
                resolve();
              } else {
                uni.showToast({
                  title: res.message,
                  duration: 2000,
                  icon: "error",
                });
                _this.back();
                rej();
              }
            });
        });
        // uni.uploadFile({
        //   url: this.action,
        //   // files: this.imageList.map((d) => ({
        //   //   name: d.file.name,
        //   //   file: d.file,
        //   //   uri: d.url,
        //   // })),
        //   file,
        //   header: {
        //     Authorization: this.vuex_tokenHead + this.vuex_token,
        //   },
        //   name: "files",
        //   success: (res) => {
        //     const data = JSON.parse(res.data);
        //     if (data.code === 200) {
        //       uni.showToast({
        //         title: "上传成功",
        //         duration: 2000,
        //       });
        //       resolve();
        //     } else {
        //       uni.showToast({
        //         title: data.message,
        //         duration: 2000,
        //         icon: "error",
        //       });
        //       rej();
        //     }
        //   },
        // });
      });
    },
  },
};
</script>

<style lang="scss">
.good-photo {
  background-color: #fff;
  padding: 50rpx 23rpx;
  height: 100%;

  .pre-box {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .pre-item {
    // flex: 0 0 33.33%;
    margin: 17rpx;
    width: 200rpx;
    height: 200rpx;
    background: #84868b;
    border-radius: 10rpx;
    overflow: hidden;
    position: relative;

    &-remove {
      width: 32rpx;
      height: 32rpx;
      position: absolute;
      right: 10rpx;
      top: 10rpx;
      z-index: 99;
    }
  }

  .pre-item-image {
    width: 100%;
    height: 100%;
  }

  .add-btn {
    width: 54rpx;
    height: 54rpx;
  }

  .slot-btn {
    margin: 17rpx;
    background: #f5f7f9;
    border: 2px dashed #dbe2f0;
    width: 200rpx;
    height: 200rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: rgb(244, 245, 246);
    border-radius: 10rpx;
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 400;
    color: #bfc7d5;
    line-height: 42rpx;
  }

  .slot-btn__hover {
    background-color: rgb(235, 236, 238);
  }

  .upload-btn {
    width: 600rpx;
    height: 80rpx;
    background: linear-gradient(90deg, #4aabf6, #4675f6);
    box-shadow: 0rpx 16rpx 30rpx 0rpx rgba(74, 169, 246, 0.2);
    border-radius: 40rpx;
    font-size: 34rpx;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 80rpx;
    color: #ffffff;
    position: fixed;
    text-align: center;
    left: 75rpx;
    bottom: 150rpx;
  }
  .task-modal {
    width: 600rpx;
    padding-bottom: 60rpx;
    // height: 480rpx;
    background: #ffffff;
    border-radius: 20rpx;
    position: relative;
    text-align: center;

    &-icon {
      position: absolute;
      height: 37rpx;
      width: 36rpx;
      right: 38rpx;
      top: 40rpx;
    }

    &-head {
      font-size: 32rpx;
      font-family: PingFang SC;
      font-weight: 600;
      color: #4b4b4b;
      line-height: 40rpx;
      margin-bottom: 60rpx;
      padding-top: 57rpx;
    }

    &-body {
      .concat {
        margin-bottom: 46rpx;
      }
    }

    &-desc {
      margin-top: 23rpx;
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: 400;
      color: #4b4b4b;
      line-height: 40rpx;
    }

    &-area {
      text-align: left;
      padding: 22rpx 21rpx;
      box-sizing: border-box;
      width: 491rpx;
      height: 141rpx;
      background: #ffffff;
      border: 1rpx solid #d4d4d4;
      border-radius: 10px;
      margin: 0 auto;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 28rpx;
    }

    &-input {
      text-align: left;
      padding: 32rpx 25rpx;
      box-sizing: border-box;
      width: 491rpx;
      height: 91rpx;
      background: #ffffff;
      border: 1rpx solid #d4d4d4;
      border-radius: 10px;
      margin: 0 auto 29rpx;

      /deep/.uni-input-input {
        height: 28rpx;
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
        line-height: 28rpx;
      }
    }

    &-place {
      text-align: left;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 400;
      color: #b5b5b5;
      line-height: 28rpx;
    }
    &-use {
      margin: 35rpx auto 0;
      width: 280rpx;
      height: 80rpx;
      background: linear-gradient(90deg, #4aabf6, #4675f6);
      box-shadow: 0rpx 16rpx 30rpx 0rpx rgba(74, 169, 246, 0.2);
      border-radius: 40rpx;
      font-size: 34rpx;
      font-family: PingFang SC;
      font-weight: 400;
      line-height: 80rpx;
      color: #ffffff;
    }
  }
}
</style>
